package com.sfx.concurrent.demo.concurrent.DiningPhilosophersProblem;

import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c.Philosophers")
public class Philosophers extends Thread{
    private Chopstick left;//左手筷子
    private Chopstick right;//右手筷子

    public Philosophers(String name, Chopstick left, Chopstick right) {
        super(name);
        this.left = left;
        this.right = right;
    }

    @Override
    public void run() {
        while(true) {
            if(left.tryLock()) {//尝试获取左手筷子
                try{
                    if(right.tryLock()) {//尝试获取到右手筷子
                        try{
                            //既获得了左手筷子,又获得了右手筷子.就可以吃饭了
                            eat();
                        }finally {
                            right.unlock();
                        }
                    }
                    //如果哲学家获取到了左手筷子,但是没有获取到右手筷子
                    //那么哲学家同时也会释放左手筷子
                }finally {
                    left.unlock();
                }
            }
        }
    }

    private void eat() {
        log.debug("eating...");
        try {
            Thread.sleep(200);//思考1s钟
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}